package com.ramos.kuaixiao.adapter;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.MyView.CartDialog;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.BrandInfoDB;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.db.SaleCustomerStoreDB;
import com.ramos.kuaixiao.entity.BrandInfo;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.NewCartInfo;
import com.ramos.kuaixiao.ui.CustomerStoreActivity;
import com.ramos.kuaixiao.ui.ShopDetailActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewCartAdapter extends BaseExpandableListAdapter {
    private Activity mContext;// 上下文
    private List<NewCartInfo> mParents = new ArrayList<>();// 数据源
    private List<BrandInfo> tasklist = new ArrayList<>();
    UpdateCarListener updateListener;
    private int tempPosition = -1;  //记录已经点击的CheckBox的位置
    public Map<Integer, Boolean> states = new HashMap<>();  //在这里要做判断保证只有一个RadioButton被选中
    public NewCartAdapter(Activity context, List<NewCartInfo> parents) {
        this.mContext = context;
        this.mParents = parents;
        for (NewCartInfo data : mParents) {
            Log.d("NewCartAdapter", "ParentAdapter " + data.getStoreNum());
        }
    }


    public void refresh(List<NewCartInfo> tasks) {
        this.mParents = tasks;
        notifyDataSetChanged();
    }

    public List<NewCartInfo> getTasks() {
        return mParents;
    }


    // 获得某个父项的某个子项
    @Override
    public NewCartInfo.CartInfo getChild(int groupPosition, int childPosition) {
        if (mParents.get(groupPosition).getList() == null) {
            return null;
        } else {
            return mParents.get(groupPosition).getList().get(childPosition);
        }
    }

    // 获得某个父项的某个子项的id
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    // 获得某个父项的子项数目
    @Override
    public int getChildrenCount(int groupPosition) {
        return mParents.get(groupPosition).getList() != null ? mParents.get(groupPosition).getList().size() : 0;
    }

    public ExpandableListView getExpandableListView() {
        ExpandableListView mExpandableListView = new ExpandableListView(
                mContext);
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 150);
        mExpandableListView.setLayoutParams(lp);
        mExpandableListView.setDividerHeight(0);// 取消group项的分割线
        mExpandableListView.setChildDivider(null);// 取消child项的分割线
        mExpandableListView.setGroupIndicator(null);// 取消展开折叠的指示图标
        return mExpandableListView;
    }

    @Override
    public View getChildView(final int parentPosition, final int childPosition, boolean isExpanded, View convertView,
                             ViewGroup parent) {
        final ExpandableListView childListView = getExpandableListView();
        Log.d("NewCartAdapter", "childListView " +childListView.getId());
        //获取子菜单的数据
        final ArrayList<NewCartInfo.CartInfo> childData = new ArrayList<>();
        Log.d("NewCartAdapter", "childData " + childData.size());
        final NewCartInfo.CartInfo bean = getChild(parentPosition, childPosition);
        Log.d("NewCartAdapter", "bean " + bean.getBrandInfos().size());
        childData.add(bean);
        Log.d("NewCartAdapter", "SecondCartAdapter " + childData.size());
        SecondCartAdapter adapter = new SecondCartAdapter(mContext, childData, parentPosition);
        adapter.setUpdateCarListener(new UpdateListener());
        childListView.setAdapter(adapter);
        int groupCount = childListView.getCount();

        childListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                Log.e("NewCartAdapter", groupPosition + "onGroupExpand>>");
                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        (bean.getBrandInfos().size() * 350 + 150));
                childListView.setLayoutParams(lp);
            }
        });

        childListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                Log.e("xxx", groupPosition + ">>onGroupCollapse");
                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,150);
                childListView.setLayoutParams(lp);
            }
        });

        childListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int Position, long id) {

                return false;
            }
        });

        for (int i=0; i<groupCount; i++) {
            childListView.expandGroup(i);
            Log.d("NewCartAdapter", "expandGroup " + i);
        };

        /**
         * 点击最小级菜单，调用该方法
         * */
        childListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView arg0, View arg1,
                                        int groupIndex, int childIndex, long arg4) {
                final CartDialog builder = new CartDialog(mContext, bean.getBrandInfos().get(childIndex));
                //builder.setTitle("购物车");
                builder.setNoOnclickListener("取消", new CartDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        builder.dismiss();
                    }
                });
                builder.setYesOnclickListener("确定", new CartDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        int i = builder.modifyCart();
                        Log.e("modify", "modify,i = " +i);
                        if (i == 1) {
                            tasklist.clear();
                            BrandInfoDB user = new BrandInfoDB();
                            tasklist = user.findAllShop(App.mUserId);
                            mParents = user.getAllNewCart(tasklist);
                            refresh(mParents);
                            Log.e("modify", "modify,mParents = " +mParents.size() + "," + tasklist.size());
                            notifyListeners(tasklist);
                            builder.dismiss();
                        }
                    }
                });
                builder.show();
                builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                return false;
            }
        });

        return childListView;
    }

    class UpdateListener implements SecondCartAdapter.UpdateCarListener {
        @Override
        public void update(List<BrandInfo> mListGoods) {
            refresh(new BrandInfoDB().getAllNewCart(mListGoods));
        }
    }


    static class ViewHolder {
        TextView name;
        TextView price;
        TextView store;
        ImageView icon;
        ImageView delete;
    }

    public static class GroupHolder {
        TextView tvWare;
        TextView tvMoney;
        public RadioButton checkbox;
    }

    // 获得某个父项
    @Override
    public Object getGroup(int groupPosition) {
        return mParents.get(groupPosition);
    }

    // 获得父项的数量
    @Override
    public int getGroupCount() {
        return mParents != null ? mParents.size() : 0;
    }

    // 获得某个父项的id
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        NewCartAdapter.GroupHolder groupholder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_cart, parent, false);
            groupholder = new NewCartAdapter.GroupHolder();
            groupholder.tvWare = (TextView) convertView.findViewById(R.id.tvWare);
            groupholder.tvMoney = (TextView) convertView.findViewById(R.id.tvMoney);
            groupholder.checkbox = (RadioButton) convertView.findViewById(R.id.checkbox);
            convertView.setTag(groupholder);
        } else {
            groupholder = (NewCartAdapter.GroupHolder) convertView.getTag();
        }
        groupholder.tvWare.setText(mParents.get(groupPosition).getCustomerName() + "(" + mParents.get(groupPosition).getStoreNum() + ")");
        groupholder.tvMoney.setText("￥" + App.df.format(Double.valueOf(mParents.get(groupPosition).getPrice())));
        //用于记录每个RadioButton的状态，并保证只可选一个

        //当RadioButton被选中时，将其状态记录进States中，并更新其他RadioButton的状态使它们不被选中
        groupholder.checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //把所有的按钮的状态设置为没选中
                for (int i = 0; i < mParents.size(); i++) {
                    states.put(i, false);
                }
                //然后设置点击的那个按钮设置状态为选中
                states.put(groupPosition, true);    //这样所有的条目中只有一个被选中！
                App.selectName = mParents.get(groupPosition).getCustomerName();
                notifyDataSetChanged();//刷新适配器
            }
        });
        groupholder.tvWare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("groupholder.tvWare", mParents.get(groupPosition).getCustomerName() + ","+mParents.get(groupPosition).getCustomerId());
                List<Customer> customers = new CustomerDB().findCustomerName(mParents.get(groupPosition).getCustomerName());
                SaleCustomerStoreDB db = new SaleCustomerStoreDB();
                //CustomerStoreDB db = new CustomerStoreDB();
                //此处需使用QID查询门店
                if (db.hasData() && customers.size() > 0) {
                    if(db.findAllCustomerStore(customers.get(0).getId()).size() == 0){
                        Intent intent = new Intent(mContext, ShopDetailActivity.class);
                        intent.putExtra("customer", customers.get(0));
                        mContext.startActivity(intent);
                    } else {
                        Intent intent = new Intent(mContext, CustomerStoreActivity.class);
                        intent.putExtra("customer", customers.get(0));
                        mContext.startActivity(intent);
                    }

                } else {
                    Intent intent = new Intent(mContext, ShopDetailActivity.class);

                    intent.putExtra("customer", customers.get(0));
                    mContext.startActivity(intent);
                }
            }
        });

        //上面是点击后设置状态，但是也是需要设置显示样式,通过判断状态设置显示的样式
        if (states.get(groupPosition) == null || !states.get(groupPosition)) {  //true说明没有被选中
            groupholder.checkbox.setChecked(false);
        } else {
            groupholder.checkbox.setChecked(true);
        }
        return convertView;
    }


    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    private void notifyListeners(List<BrandInfo> mListGoods) {
        updateListener.update(mListGoods);
    }

    public interface UpdateCarListener {
        void update(List<BrandInfo> mListGoods);
    }

    public void setUpdateCarListener(UpdateCarListener updateListener) {
        this.updateListener = updateListener;
    }
}